package model;

import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

public class Environment extends Source {

	private final Timer timer = new Timer("Environment");
	private Double maxValue = Constants.MAX_VALUE_DEFAULT_ENVIRONMENT;
	private Double minValue = Constants.MIN_VALUE_DEFAULT_ENVIRONMENT;
	private Double variationSpeed = Constants.SPEED_DEFAULT;
	private final Random randomGenerator = new Random();
	private String name;

	public Environment(SensedValue value, Integer id) {
		super(value, id);
		EnvironmentUpdator updator = new EnvironmentUpdator();
		timer.schedule(updator, 0, Constants.SECONDS);
	}

	public Environment(SensedValue value, Double minValue, Double maxValue, Integer id) {
		this(value, id);
		this.maxValue = maxValue;
		this.minValue = minValue;
	}

	public Environment(SensedValue value, Double minValue, Double maxValue, Double speed, Integer id) {
		this(value, minValue, maxValue, id);
		variationSpeed = speed;
	}

	@Override
	public SensedValue getValue() {
		return value;
	}

	private Double getVariation() {
		Double variation = Double.valueOf(randomGenerator.nextInt(100)) * 0.001 * variationSpeed;
		if (randomGenerator.nextInt(100) > 49) {
			variation = variation * -1;
		}
		return variation;
	}

	@Override
	public Double getMaxValue() {
		return maxValue;
	}

	@Override
	public Double getMinValue() {
		return minValue;
	}

	public void modifyValue(Double d) {
		if ((value.getValue() + d) > getMaxValue()) {
			value.setValue(getMaxValue().doubleValue());
		} else if ((value.getValue() + d) < getMinValue()) {
			value.setValue(getMinValue().doubleValue());
		} else {
			value.setValue(value.getValue() + d);
		}
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String toString() {
		if (name != null) {
			return name;
		} else {
			return super.toString();
		}
	}

	public class EnvironmentUpdator extends TimerTask {

		public EnvironmentUpdator() {
			super();
		}

		@Override
		public void run() {
			Double variation = getVariation();
			if ((value.getValue().doubleValue() + variation.doubleValue()) > getMaxValue().doubleValue()) {
				value.setValue(value.getValue().doubleValue() - variation.doubleValue());
			} else if ((value.getValue().doubleValue() + variation.doubleValue()) < getMinValue().doubleValue()) {
				value.setValue(value.getValue().doubleValue() - variation.doubleValue());
			} else {
				value.setValue(value.getValue().doubleValue() + variation.doubleValue());
			}
		}

	}

}
